package com.web.exiaodao.remote.service.impl;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.*;
import com.web.exiaodao.business.repository.*;
import com.web.exiaodao.remote.vo.ShareRecordTableVo;

import java.util.List;
import java.util.Map;

import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.remote.service.ApishareRecordTableService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APIShareRecordTable接口实现类
 **/
@Service("ApiShareRecordTableService")
@Transactional(readOnly = false)
public class ApiShareRecordTableServiceImpl extends BaseService<ShareRecordTable> implements ApishareRecordTableService {

    private static final Logger LOGGER = Logger.getLogger(ApiShareRecordTableServiceImpl.class);

    @Autowired
    ShareRecordTableRepository shareRecordTableRepository;
    @Autowired
    ServiceCommonRepository serviceCommonRepository;
    @Autowired
    ServiceDomesticNursingRepository domesticNursingRepository;
    @Autowired
    ServiceNurseTrainingRepository nurseTrainingRepository;
    @Autowired
    VSDCRepository vsdcRepository;
    @Autowired
    InstitutionRepository institutionRepository;
    @Autowired
    InsHotelRoomsTableRepository insHotelRoomsTableRepository;
    @Autowired
    BannerRepository bannerRepository;
    @Autowired
    ShopRepository shopRepository;
    @Autowired
    ArtInformationRepository artInformationRepository;//作者
    @Autowired
    AutherWorksTableRepository autherWorksTableRepository;//作品
    @Autowired
    TravelTableRepository travelTableRepository;

    @Override
    public XaResult<ShareRecordTableVo> findOne(Long tId) throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }

    @Override
    public XaResult<List<ShareRecordTableVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.NE, status));
        Page<ShareRecordTable> page = shareRecordTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), ShareRecordTable.class), pageable);
        XaResult<List<ShareRecordTableVo>> xr = new XaResult<List<ShareRecordTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), ShareRecordTableVo.class));
        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->ShareRecordTable");
        return xr;
    }


    @Override
    public XaResult<Page<ShareRecordTableVo>> findListEQUStatusByFilterPage(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        Page<ShareRecordTable> page = shareRecordTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), ShareRecordTable.class), pageable);
        XaResult<Page<ShareRecordTableVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), ShareRecordTableVo.class)));
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->ShareRecordTable");
        return xr;
    }

    @Override
    public XaResult<List<ShareRecordTableVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        Page<ShareRecordTable> page = shareRecordTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), ShareRecordTable.class), pageable);
        XaResult<List<ShareRecordTableVo>> xr = new XaResult<List<ShareRecordTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), ShareRecordTableVo.class));
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->ShareRecordTable");
        return xr;
    }

    @Override
    public XaResult<ShareRecordTableVo> multiOperate(String modelIds,
                                                     Integer status) throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }

    @Override
    public XaResult<ShareRecordTableVo> createModel(ShareRecordTable model)
            throws BusinessException {
        XaResult<ShareRecordTableVo> xr = new XaResult<ShareRecordTableVo>();

        //查询详情信息
        int shareType = model.getShareType();
        String shareName = "";
        String shareURL = "";
        switch (shareType) {
            case JConstant.Search_Share_FavType.SERVICE: {
                ServiceCommon en = serviceCommonRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getTitle();
                shareURL = en.getImg();
            }
            break;
            case JConstant.Search_Share_FavType.SERVICE_DOMESITC_NURSING: {
                ServiceDomesticNursing en = domesticNursingRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getNurse_Name();
                shareURL = en.getNurse_PicUrl();
            }
            break;
            case JConstant.Search_Share_FavType.NURSE_TRANING: {
                ServiceNurseTraining en = nurseTrainingRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getNurseTraining_Name();
                shareURL = en.getNurseTraining_url();
            }
            break;
            case JConstant.Search_Share_FavType.NURSE_VSDC: {
                VSDC en = vsdcRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getVsdc_Name();
                shareURL = en.getVsdc_PicURL();
            }
            break;
            case JConstant.Search_Share_FavType.INSTIBUTION: {
                Institution en = institutionRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getInstitution_Name();
                shareURL = en.getInstitution_pic();
            }
            break;
            case JConstant.Search_Share_FavType.HOURSE: {
                InsHotelRoomsTable en = insHotelRoomsTableRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getHotelRooms_Name();
                List<Banner> banner = bannerRepository.findByobjectIdAndTypeAndStatusNot(model.getShareObjectId(), JConstant.BannerType.INSTITUTION_HOURSE, XaConstant.Status.delete);
                if (XaUtil.isNotEmpty(banner)) {
                    shareURL = banner.get(0).getPicurl();
                }
            }
            break;
            case JConstant.Search_Share_FavType.GOODS: {
                Shop en = shopRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getShopProductName();
                if (XaUtil.isNotEmpty(en.getShopProductPicUrls())) {
                    shareURL = en.getShopProductPicUrls().split(JConstant.SYMBOL_DOT)[0];
                }
            }
            break;
            case JConstant.Search_Share_FavType.ARTWORK: {
                AutherWorksTable en = autherWorksTableRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getWorksName();
                if (XaUtil.isNotEmpty(en.getWorksImgs())) {
                    shareURL = en.getWorksImgs().split(JConstant.SYMBOL_DOT)[0];
                }
            }
            break;
            case JConstant.Search_Share_FavType.ARTWORK_AUTHOR: {
                ArtInformation en = artInformationRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getAuthorName();
                shareURL = en.getAuthorIconPic();
            }
            break;
            case JConstant.Search_Share_FavType.TOUR: {
                TravelTable en = travelTableRepository.findByIdAndStatusNot(model.getShareObjectId(), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getShareObjectId() + ")");
                    return xr;
                }
                shareName = en.getTravelItemName();
                List<Banner> banners = bannerRepository.findByobjectIdAndTypeAndStatusNot(model.getShareObjectId(), JConstant.BannerType.TRAVEL, XaConstant.Status.delete);
                if (XaUtil.isNotEmpty(banners)) {
                    shareURL = banners.get(0).getPicurl();
                }
            }
            break;
        }

        try {
            int lenght = ReflectionUtils.getHibernateColumnAnnotationLength(ShareRecordTable.class, "shareName");
            model.setShareName(shareName.length() > lenght ? shareName.substring(0, lenght) : shareName);
            model.setShareUrl(shareURL);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getLocalizedMessage());
        }

        ShareRecordTable obj = shareRecordTableRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), ShareRecordTableVo.class));
        xr.getObject().
                setId(obj.getId());
        LOGGER.info("新增数据成功----->ShareRecordTable");
        return xr;
    }

    @Override
    public XaResult<ShareRecordTableVo> updateModel(ShareRecordTable model)
            throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }
}
